package edu.wpi.first.wpilibj.swarm;
import com.sun.squawk.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;

public class LoggerServer implements Runnable {
	private ServerSocketConnection serverport;
	private SocketConnection       connection;
	private BufferedWriter             output;
	private String                     header;
	
	public LoggerServer(String header) {
		this.header = header;
		try {
			serverport = (ServerSocketConnection) Connector.open("socket://:5505");
		} catch (IOException ex) {
			System.out.println(ex);
		}
		connection = null;
		init();
	}

	public void logString(String data) {
		synchronized(this) {
			if (output == null) return;
			try {
				output.write(data);
			} catch (IOException ex) {
				output = null;
			}
		}
	}
	
	private void init() {
		new Thread(this).start();
	}

	public void run() {
		while (true) {
			try {
				connection = (SocketConnection) serverport.acceptAndOpen();
				synchronized(this) {
					if (output != null) output.close();
					output = new BufferedWriter(
					         new OutputStreamWriter(
					         connection.openOutputStream()));
					output.write(header + "\n");
				}
			} catch (IOException ex) {
				System.out.println(ex);
				output = null;
			}
		}
	}
}